package cn.uniqueinfo.dp.controller;

import cn.uniqueinfo.dp.controller.base.BaseController;
import cn.uniqueinfo.dp.service.IDeptService;
import cn.uniqueinfo.dp.vo.DeptVO;
import cn.uniqueinfo.dp.vo.EasyuiTableResult;
import cn.uniqueinfo.dp.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;

/**
 * @author:朱元勋
 * @mail:395910063@qq.com
 * @date:2019-01-29 14:47:12
 * @description:部门
 */
@Slf4j
@Controller
@RequestMapping(value = "/dept")
public class DeptController extends BaseController<DeptVO> {
    private IDeptService service;

    public DeptController(IDeptService service) {
        this.service = service;
        this.baseService = service;
        this.ctlName = "dept";
        this.tipName = "部门";
    }

    @GetMapping("/tree")
    @ResponseBody
    public EasyuiTableResult<DeptVO> findTree() {
        EasyuiTableResult<DeptVO> tableResult = new EasyuiTableResult<>();
        List<DeptVO> rows = this.service.findAll(null);
        tableResult.setRows(rows);
        tableResult.setTotal((long) rows.size());
        return tableResult;
    }

    @PostMapping("/treeSave")
    @ResponseBody
    public Result treeSave(@Valid DeptVO item, String ppath, BindingResult bindingResult) {
        if (item.getId() == 0) {
            item.setPath("");
            Result result = onAdd(item, "save", bindingResult);
            if (result.getCode() == 1) {
                Long id = (Long) result.getData();
                if (item.getIpid() == 0) {
                    this.service.updatePath(id + ".", id);
                } else {
                    this.service.updatePath(ppath + "" + id + ".", id);
                }
            }
            return result;
        } else {
            Result result = onEdit(item, "save", bindingResult);
            if (result.getCode() == 1) {
                if (item.getIpid() == 0) {
                    this.service.updatePath(item.getId() + ".", item.getId());
                } else {
                    if (ppath != null && ppath != "") {
                        this.service.updatePath(ppath + "" + item.getId() + ".", item.getId());
                    }
                }
            }
            return result;
        }
    }
}
